package com.baweiwei.ordersapi.controller;

import cn.hutool.core.lang.Snowflake;
import com.baweiwei.common.entity.Good;
import com.baweiwei.common.entity.OrderDetail;
import com.baweiwei.common.entity.Orders;
import com.baweiwei.common.entity.Users;
import com.baweiwei.ordersapi.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @RequestMapping("/save")
    public Map<String,Object> orders(){
//模拟订单
        Users users1 = new Users();
        users1.setId(1); //模拟的用户

        Orders orders1 = new Orders();

        Snowflake snowflake = new Snowflake();
        //订单号
        orders1.setOrderId("BW"+snowflake.nextIdStr());
        //订单时间
        orders1.setCreated(new Date());
        orders1.setUsers(users1);




        List<OrderDetail> orderDetails = new ArrayList<>();
        //创建订单详情
        OrderDetail orderDetail1 = new OrderDetail();

        Good good1 = new Good();
        good1.setGoodId(1);
        //设置商品
        orderDetail1.setGood(good1);   //1  100 -2  98库存
        orderDetail1.setNum(2); //购买的数量
        orderDetail1.setPrice(new BigDecimal(200));//购买的价格
        orderDetail1.setTotal(orderDetail1.getPrice().multiply(new BigDecimal(orderDetail1.getNum()))); //400
        //设置订单
        orderDetail1.setOrders(orders1);
        orderDetails.add(orderDetail1);



        //创建订单详情
        OrderDetail orderDetail2 = new OrderDetail();

        Good good2 = new Good();
        good2.setGoodId(2); //      库存 -1  9
        //设置商品
        orderDetail2.setGood(good2);
        orderDetail2.setNum(1);
        orderDetail2.setPrice(new BigDecimal(300));
        orderDetail2.setTotal(orderDetail2.getPrice().multiply(new BigDecimal(orderDetail2.getNum())));
        //设置订单
        orderDetail2.setOrders(orders1);
        orderDetails.add(orderDetail2);

        //订单的 详情集合
        orders1.setOrderDetails(orderDetails);

        //订单的总数量
        orders1.setNum(orderDetails.stream().mapToLong(x->x.getNum()).sum());
        //订单的总金额
        orders1.setTotal(orderDetails.stream().map(vo -> ObjectUtils.isEmpty(vo.getTotal()) ? new BigDecimal(0) : vo.getTotal()).reduce(BigDecimal.ZERO, BigDecimal::add));

        ordersService.addOrder(orders1);

        Map<String,Object> map = new HashMap<>();
        map.put("data",true);
        return map;

    }
}
